package com.cliang.servlet;

import com.cliang.tools.db.DB;
import com.cliang.entity.BlogUser;
import com.cliang.tools.encription.Encription;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class UserLoginServlet extends HttpServlet{
    private static final long serialVersionUID=1L;

    private ArrayList<BlogUser> loginedUsers=null;
    private ServletContext servletContext=null;

    public UserLoginServlet(){
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       req.setCharacterEncoding("UTF-8");
       resp.setCharacterEncoding("UTF-8");
       resp.setContentType("text/html;charset= utf-8");
       String userName=req.getParameter("username");
       String password=req.getParameter("password");
       String verifyCode=req.getParameter("code");


        //在项目启动第一次时创建，该项目只创建一次，唯一的
        servletContext=this.getServletContext();
        boolean isLogined=false;            //false未登录
        loginedUsers= (ArrayList<BlogUser>) servletContext.getAttribute("blogUsers");

//        if(null==req.getSession(false)){
//            if(true==req.getSession(true).isNew()){
//
//            }else {
//                //session过期
//            }
//        }

        if(loginedUsers!=null){
            for(BlogUser user:loginedUsers){
                if(user.getBuNickname().equals(userName) && null==req.getSession(false) && true==req.getSession(true).isNew())
                    isLogined=true;
            }
        }else {
            loginedUsers=new ArrayList<>();
        }

       if(!isLogined){
           HttpSession session=req.getSession();
           PrintWriter printWriter=resp.getWriter();
           if(!verifyCode.toLowerCase().equals(session.getAttribute("verifyCode").toString().toLowerCase())){
               printWriter.print("<script language=javascript> alert('验证码错误！');window.location.href='/Blog/login/login.html'</script>");
//           req.getRequestDispatcher("/Blog/login/login.html").forward(req,resp);
           }

           BlogUser blogUser=new BlogUser();

           Connection conn= DB.getConnection();
           if(conn!=null){
               try {
                   PreparedStatement psmt=conn.prepareStatement("select Bu_id,Bu_nickname,Bu_name,Bu_password,Bu_email,Bu_picture,Bu_time from blog_user where Bu_nickname=?");
                   psmt.setString(1,userName);
                   ResultSet rs=null;
                   rs=psmt.executeQuery();
                   if(rs!=null)while(rs.next()){
                       blogUser.setBuId(rs.getInt("Bu_id"));
                       blogUser.setBuNickname(rs.getString("Bu_nickname"));
                       blogUser.setBuName(rs.getString("Bu_name"));
                       blogUser.setBuPassword(rs.getString("Bu_password"));
                       blogUser.setBuEmail(rs.getString("Bu_email"));
                       blogUser.setBuPicture(rs.getString("Bu_picture"));
                       blogUser.setBuTime(rs.getString("Bu_time"));
                   }
               } catch (SQLException e) {
                   e.printStackTrace();
               }
               DB.close(conn);
           }else {
               printWriter.print("<script language=javascript> alert('系统内部错误，请稍后重试！');</script>");
               req.getRequestDispatcher("/Blog/login/login.html").forward(req,resp);
           }

           if(!Encription.encodeByMD5(password).equals(blogUser.getBuPassword())){
               printWriter.print("<script language=javascript> alert('密码错误！');</script>");
               req.getRequestDispatcher("/Blog/login/login.html").forward(req,resp);

           }else{
           session.setAttribute("blogUser",blogUser);
           loginedUsers.add(blogUser);
           servletContext.setAttribute("blogUsers",loginedUsers);

           req.getRequestDispatcher("/Blog/private/blog/main.html").forward(req,resp);

           }

        printWriter.close();
       }else{
            //已经登录
           resp.sendRedirect("/Blog/private/blog/main.html");
       }
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }
}
